import Request from "./request.js"
import apiList from "./api.js"
import store from "@/store/index.js"
import tools from '@/common/utils/tools.js';
export default function api (url, data = {}) {
    const request = new Request();
    let api = getApiObj(url);
	let user_id = store.state.member.info.member_id;
    // 请求之前拦截器
    request.interceptor.request((config, cancel) => {
        config.data.timestamp = tools.timestamp();                  // 时间戳
        config.data.noncestr = tools.randstr();                     // 随机字符串
		if (api.member) {
			config.data.member_id = user_id;                        // 会员ID
            config.data.signature = tools.make_sign(config.data);   // 签名
		}
    	return config
    });
    // 请求之后拦截器
    request.interceptor.response((response) => {
        let data
        if (response.data != Object) {
            data = JSON.parse(response.data);
        }
        return data
    }, (response) => {
        return response
    })
    return request.request({
        url:api.url,
        data,
        method: api.method
    })
}

function getApiObj(url) {
    let apiArray = url.split(".");
    let api = apiList;
    apiArray.forEach(v => {
        api = api[v]
    })
    return api;
}

